const router = require('express').Router();
const socketio = require('../../../socket');
const { dbQuery, dbError, sqlStrQuotationHandle } = require('../../../tools');


router.get('/', async function(req, res) {
	const {user_id, group_id, message} = req.query;


    function checkSended() {
        return new Promise((resolve, reject) => {
            // 不重复添加加入消息
            dbQuery(`
                select message_id 
                from system_message_table 
                where about_user_id='${user_id}' and about_group_id='${group_id}' and message_type='1' and checked='0'`
            )
            .then(data => {
                resolve(data);
            })
            .catch(err => {
                reject(err);
            });
        })
    }
    const result = await checkSended();
    if (Object.prototype.toString.call(result) !== '[object Array]') {
        res.send({code: 0, message: '数据库错误'});
        return;
    }
    if (result.length > 0) {
        console.log(result)
        res.send({code: 1, message: '加入群组请求已发送'});
        return;
    }

    const admins = await dbQuery(`select admin from group_table where group_id='${group_id}'`);
    const adminsIDArr = admins[0].admin.split(',');

    const checkMessage = adminsIDArr.map(id => {
        return dbQuery(`
            insert into system_message_table 
            (
                user_id,message_content,send_time,message_type,about_group_id,about_user_id,add_message
            )
            values 
            (
                '${id}','申请加入群组',DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'),'${1}','${group_id}','${user_id}','${sqlStrQuotationHandle(message)}'
            )
        `);
    });

    
	
    Promise.all([
        dbQuery(`select name as user_name,avator as user_avator from user_table where id='${user_id}'`),
        dbQuery(`select group_name, group_avator from group_table where group_id='${group_id}'`)
    ])
    .then(async data => {
        try {
            // 只要有一个管理员有消息既为成功
            await Promise.race(checkMessage);
             // 发送成功则触发socket发送消息
            adminsIDArr.forEach(id => {
                socketio().toEmit(`systemMessage${id}`, socketio().connectUser[id], {
                    about_user_id: +user_id,
                    user_name: data[0][0].user_name,
                    user_avator: data[0][0].user_avator,
                    about_group_id: +group_id,
                    group_name: data[1][0].group_name,
                    group_avator: data[1][0].group_avator,

                    link_url: null,
                    message_content: "申请加入群组",
                    add_message: message,
                    message_type: "1",
                    name: "系统消息",
                    avator: "system_message",
                    message_id: Math.random(),
                    send_time: new Date(),
                    checked: "0",
                    user_id: +id
                });
            });
        } catch(err) {
            dbError(res, err);
            return;
        }
       
        res.send({code: 1, message: '加入群组请求已发送'});
    })
    .catch(err => {
        dbError(res, err);
    });
});
router.get('/checked', async function(req, res) {
    const {user_id, group_id, confirm} = req.query;
    // 是否将用户加入群组
    if (confirm === 'true') {
        await dbQuery(`
            insert into member_table 
        	(group_id, user_id, check_time) 
        	values 
        	(${group_id}, ${user_id},DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'))
        `);
    }

    dbQuery(`update system_message_table set checked='1' where about_group_id='${group_id}' and about_user_id='${user_id}'`)
    .then(updateData => {
        if (updateData.changeRows === 0) {
            res.send({code: 1, message: '数据库错误'});
            return;
        }
        if (confirm === 'true') {
            dbQuery(`
                select m.message_content,m.send_time,g.*,u.name
                from user_table u,
                (select group_name,group_id,group_avator from group_table where group_id='${group_id}') g,
                (select user_id,message_content,send_time from message_table where group_id='${group_id}' ORDER BY send_time desc) m
                where u.id=m.user_id
                order by m.send_time desc
                limit 1
            `)
            .then(data => {
                // 这里不管出错
                dbQuery(`
                    insert into system_message_table 
                    (user_id,message_content,message_type) 
                    values 
                    ('${user_id}','你已加入群组${data[0].group_name}','0')
                `)
                .catch(err => {
                    console.log(err, '加入群组系统消息发送失败');
                });
          
                socketio().toEmit('joinGroup', socketio().connectUser[user_id], data[0]);
                socketio().toEmit(`systemMessage${user_id}`, socketio().connectUser[user_id], {
                    name:'系统消息',
                    avator: 'system_message',
                    checked: 0,
                    message_type: '0',
                    message_content: `你已加入群组${data[0].group_name}`,
                    send_time: new Date(),
                    user_id: +user_id
                });
            });
        }
        res.send({code: 1, message: '已处理'});
    })
    .catch(err => {
        dbError(res, err);
    });
});


module.exports = router;

